package com.example.myapplication.livedata.model;

import android.os.Bundle;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.SavedStateHandle;
import androidx.lifecycle.ViewModel;
import androidx.savedstate.SavedStateRegistry;

import com.example.myapplication.bean.ProductInfo;

/**
 * Created by xiaolong on 2022/1/13 8:16 下午
 * email：xinxiaolong123@foxmail.com
 */
public class SavedStateViewModel extends ViewModel {


    public MutableLiveData<ProductInfo> product_1 = new MutableLiveData<>();

    public MutableLiveData<ProductInfo> product_2;

    private SavedStateHandle state;

    public SavedStateViewModel(SavedStateHandle savedStateHandle) {
        //主动set的方式进行保存
        product_1 = restoreProduct1(savedStateHandle);
        //实现了SavedStateProvider进行的保存
        product_2 = restoreProduct2(savedStateHandle.get("product_provide"));
        savedStateHandle.setSavedStateProvider("product_provide", new ProductSavedStateProvider());
        state = savedStateHandle;
    }

    public void setProduct1(ProductInfo productInfo) {
        product_1.setValue(productInfo);
        state.set("product_1", product_1.getValue());
    }

    public void setProduct2(ProductInfo productInfo) {
        this.product_2.setValue(productInfo);
    }


    @Nullable
    private MutableLiveData<ProductInfo> restoreProduct1(SavedStateHandle savedStateHandle) {
        if (savedStateHandle != null && savedStateHandle.contains("product_1")) {
            return savedStateHandle.getLiveData("product_1");
        }
        return new MutableLiveData<>();
    }

    @Nullable
    private MutableLiveData<ProductInfo> restoreProduct2(Bundle bundle) {
        MutableLiveData<ProductInfo> m = new MutableLiveData<>();
        if (bundle != null && bundle.containsKey("product_2")) {
            ProductInfo productInfo = (ProductInfo) bundle.get("product_2");
            m.setValue(productInfo);
        }
        return m;
    }

    private class ProductSavedStateProvider implements SavedStateRegistry.SavedStateProvider {

        @NonNull
        @Override
        public Bundle saveState() {
            Bundle bundle = new Bundle();
            bundle.putSerializable("product_2", product_2.getValue());
            return bundle;
        }
    }
}
